package com.lekang.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.Balance;
import com.lekang.system.service.IBalanceService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 余额查询Controller
 * 
 * @author 刘卓
 * @date 2025-10-14
 */
@RestController
@RequestMapping("/system/balance")
public class BalanceController extends BaseController
{
    @Autowired
    private IBalanceService balanceService;

    /**
     * 查询余额查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:balance:list')")
    @GetMapping("/list")
    public TableDataInfo list(Balance balance)
    {
        startPage();
        List<Balance> list = balanceService.selectBalanceList(balance);
        return getDataTable(list);
    }

    /**
     * 导出余额查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:balance:export')")
    @Log(title = "余额查询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Balance balance)
    {
        List<Balance> list = balanceService.selectBalanceList(balance);
        ExcelUtil<Balance> util = new ExcelUtil<Balance>(Balance.class);
        util.exportExcel(response, list, "余额查询数据");
    }

    /**
     * 获取余额查询详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:balance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(balanceService.selectBalanceById(id));
    }

    /**
     * 新增余额查询
     */
    @PreAuthorize("@ss.hasPermi('system:balance:add')")
    @Log(title = "余额查询", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Balance balance)
    {
        return toAjax(balanceService.insertBalance(balance));
    }

    /**
     * 修改余额查询
     */
    @PreAuthorize("@ss.hasPermi('system:balance:edit')")
    @Log(title = "余额查询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Balance balance)
    {
        return toAjax(balanceService.updateBalance(balance));
    }

    /**
     * 删除余额查询
     */
    @PreAuthorize("@ss.hasPermi('system:balance:remove')")
    @Log(title = "余额查询", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(balanceService.deleteBalanceByIds(ids));
    }

    /**
     * 根据老人ID查询余额信息（用于账单调整的杂费卡片）
     */
    @PreAuthorize("@ss.hasPermi('system:balance:query')")
    @GetMapping("/elderly/{elderlyId}")
    public AjaxResult getBalanceByElderlyId(@PathVariable("elderlyId") Long elderlyId)
    {
        try {
            System.out.println("=== 查询老人余额信息 ===");
            System.out.println("老人ID: " + elderlyId);

            // 查询条件：老人ID
            Balance queryBalance = new Balance();
            queryBalance.setElderlyId(elderlyId);

            System.out.println("=== 查询条件 ===");
            System.out.println("老人ID: " + elderlyId);

            List<Balance> balances = balanceService.selectBalanceList(queryBalance);
            System.out.println("查询到的余额记录数量: " + (balances != null ? balances.size() : 0));

            if (balances != null && !balances.isEmpty()) {
                System.out.println("✅ 找到余额记录，数量: " + balances.size());

                // 取第一条记录（通常一个老人只有一条余额记录）
                Balance balance = balances.get(0);
                System.out.println("=== 余额详细信息 ===");
                System.out.println("余额ID: " + balance.getId());
                System.out.println("老人ID: " + balance.getElderlyId());
                System.out.println("预交款余额: " + balance.getPrepaymentBalance());
                System.out.println("押金余额: " + balance.getDepositBalance());

                // 构建返回数据
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("id", balance.getId());
                result.put("elderlyId", balance.getElderlyId());
                result.put("prepaymentBalance", balance.getPrepaymentBalance()); // 预交款余额
                result.put("depositBalance", balance.getDepositBalance());       // 押金余额
                result.put("depositAmount", balance.getDepositBalance());        // 押金数（与押金余额相同）

                System.out.println("=== 返回数据 ===");
                System.out.println("押金余额: " + balance.getDepositBalance());
                System.out.println("预交款余额: " + balance.getPrepaymentBalance());
                System.out.println("=== 余额查询完成 ===");
                
                return success(result);
            } else {
                System.out.println("未找到该老人的余额记录");
                
                // 返回默认值
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("id", null);
                result.put("elderlyId", elderlyId);
                result.put("prepaymentBalance", java.math.BigDecimal.ZERO);
                result.put("depositBalance", java.math.BigDecimal.ZERO);
                result.put("depositAmount", java.math.BigDecimal.ZERO);
                
                return success(result);
            }

        } catch (Exception e) {
            System.out.println("查询余额信息异常: " + e.getMessage());
            e.printStackTrace();
            return error("查询余额信息失败：" + e.getMessage());
        }
    }

    /**
     * 更新老人预交款余额（用于账单调整提交后）
     */
    @PreAuthorize("@ss.hasPermi('system:balance:edit')")
    @Log(title = "更新老人预交款余额", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping("/updatePrepaymentBalance")
    public AjaxResult updatePrepaymentBalance(@RequestBody java.util.Map<String, Object> params)
    {
        try {
            System.out.println("=== 更新老人预交款余额 ===");
            
            Long elderlyId = Long.valueOf(params.get("elderlyId").toString());
            java.math.BigDecimal refundAmount = new java.math.BigDecimal(params.get("refundAmount").toString());
            
            System.out.println("老人ID: " + elderlyId);
            System.out.println("实际应退金额: " + refundAmount);
            
            // 查询老人的余额记录
            Balance queryBalance = new Balance();
            queryBalance.setElderlyId(elderlyId);
            List<Balance> balances = balanceService.selectBalanceList(queryBalance);
            
            if (balances != null && !balances.isEmpty()) {
                Balance balance = balances.get(0);
                System.out.println("=== 更新前余额信息 ===");
                System.out.println("余额ID: " + balance.getId());
                System.out.println("原预交款余额: " + balance.getPrepaymentBalance());
                
                // 计算新的预交款余额：原余额 + 实际应退金额
                java.math.BigDecimal newPrepaymentBalance = balance.getPrepaymentBalance().add(refundAmount);
                balance.setPrepaymentBalance(newPrepaymentBalance);
                
                System.out.println("=== 更新后余额信息 ===");
                System.out.println("新预交款余额: " + newPrepaymentBalance);
                
                // 更新余额记录
                System.out.println("=== 开始更新数据库 ===");
                System.out.println("更新对象ID: " + balance.getId());
                System.out.println("更新对象预交款余额: " + balance.getPrepaymentBalance());
                
                int result = balanceService.updateBalance(balance);
                System.out.println("数据库更新结果: " + result);
                
                if (result > 0) {
                    System.out.println("✅ 老人预交款余额更新成功！");
                    
                    // 验证更新结果
                    Balance verifyBalance = balanceService.selectBalanceById(balance.getId());
                    System.out.println("=== 验证更新结果 ===");
                    System.out.println("验证后的预交款余额: " + verifyBalance.getPrepaymentBalance());
                    
                    // 构建返回数据
                    java.util.Map<String, Object> responseData = new java.util.HashMap<>();
                    responseData.put("elderlyId", elderlyId);
                    responseData.put("originalBalance", balance.getPrepaymentBalance().subtract(refundAmount));
                    responseData.put("refundAmount", refundAmount);
                    responseData.put("newBalance", newPrepaymentBalance);
                    responseData.put("verifiedBalance", verifyBalance.getPrepaymentBalance());
                    
                    return success(responseData);
                } else {
                    System.out.println("❌ 老人预交款余额更新失败");
                    return error("老人预交款余额更新失败");
                }
            } else {
                System.out.println("❌ 未找到该老人的余额记录");
                return error("未找到该老人的余额记录");
            }
            
        } catch (Exception e) {
            System.out.println("更新老人预交款余额异常: " + e.getMessage());
            e.printStackTrace();
            return error("更新老人预交款余额失败：" + e.getMessage());
        }
    }
}
